package com.wang.tool.invoker;

import com.wang.tool.util.CommonUtil;

import java.util.List;
import java.util.function.Consumer;

/**
 * @Description 循环执行器
 * @Author shaopeng
 * @Date 2021/6/11
 * @Version 1.0
 */
public class CycleInvoker {

    /**
     * 批量处理
     *
     * @param params   总参数
     * @param pageSize 单次数量
     * @param process  处理逻辑
     * @param <P>      入参
     * @return
     */
    public static <P> void pageProcess(List<P> params, int pageSize, Consumer<List<P>> process) {
        if (pageSize < 1) {
            throw new IllegalArgumentException("pageSize can not small 1");
        }
        if (process == null) {
            throw new IllegalArgumentException("query can not be null");
        }
        if (CommonUtil.isEmpty(params)) {
            return;
        }
        int totalSize = params.size();
        if (totalSize <= pageSize) {
            process.accept(params);
            return;
        }

        //总的次数
        int allTime = (totalSize + pageSize - 1) / pageSize;
        for (int i = 0; i < allTime; i++) {
            int toIndex = Math.min((i + 1) * pageSize, totalSize);
            List<P> oneParams = params.subList(i * pageSize, toIndex);
            process.accept(oneParams);
        }
    }

}
